package jike.demo11.pingxue.service;

import jike.demo11.pingxue.Bo.VirtualWalletBo;
import jike.demo11.pingxue.entity.VirtualWalletEntity;
import jike.demo11.pingxue.exception.NoSufficientBalanceException;
import jike.demo11.pingxue.repository.VirtualWalletRepository;
import jike.demo11.pingxue.repository.VirtualWalletTransactionRepository;

import java.math.BigDecimal;

/**
 * @author oyz
 */
public class VirtualWalletService {

    // 通过构造函数或者 IOC 框架注入
    private VirtualWalletRepository walletRepo;
    private VirtualWalletTransactionRepository transactionRepo;

    public VirtualWalletBo getVirtualWallet(Long walletId) {
        VirtualWalletEntity walletEntity = walletRepo.getWalletEntity(walletId);
        VirtualWalletBo walletBo = Convert(walletEntity);
        return walletBo;
    }


    VirtualWalletBo Convert(VirtualWalletEntity walletEntity) {
        return null;
    }

    public BigDecimal getBalance(Long walletId) {
        return walletRepo.getBalance(walletId);
    }


    public void debit(Long walletId, BigDecimal amount) throws NoSufficientBalanceException {
        VirtualWalletEntity walletEntity = walletRepo.getWalletEntity(walletId);
        BigDecimal balance = walletEntity.getBalance();
        if (balance.compareTo(amount) < 0) {
            throw new NoSufficientBalanceException("钱不够了");
        }
        walletRepo.updateBalance(walletId, balance.subtract(amount));
    }

    public void credit(Long walletId, BigDecimal amount) {
        VirtualWalletEntity walletEntity = walletRepo.getWalletEntity(walletId);
        BigDecimal balance = walletEntity.getBalance();
        walletRepo.updateBalance(walletId, balance.add(amount));
    }

    public void transfer(Long fromWalletId, Long toWalletId, BigDecimal amount){
        // TODO 执行转账的业务逻辑
    }

}
